package com.czy.owner.ui.packagecardproject;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.PackageCardProjectAdapter;
import com.czy.owner.adapter.PackageCardProjectAdapter2;
import com.czy.owner.api.OwnerPacStoreServicePackageApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.PackageCardProjectModel;
import com.czy.owner.entity.SelectBespokeListModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2017/4/17 0017.
 * 门店套餐卡项
 */
public class PackageCardProjectActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView easyRecyclerView;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_give_price)
    TextView tvGivePrice;
    private PackageCardProjectAdapter2 adapter = null;
    private Handler handler = new Handler();
    private int page = 1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_store_package;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("门店卡项套餐");
        RxBus.getDefault().register(this);
        initRecycleView();
    }

    @Override
    protected void updateViews() {

    }

    private void initRecycleView() {
        easyRecyclerView.setLayoutManager(new LinearLayoutManager(PackageCardProjectActivity.this));
        easyRecyclerView.setAdapterWithProgress(adapter = new PackageCardProjectAdapter2(PackageCardProjectActivity.this));
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                //adapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                adapter.resumeMore();
            }
        });

        adapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();

            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();

            }
        });
        easyRecyclerView.setRefreshListener(this);
        onRefresh();

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<PackageCardProjectModel>() {
            @Override
            public void onItemClick(View view, int position, PackageCardProjectModel model) {
                if (PhoneUtils.isNetworkConnected(PackageCardProjectActivity.this)) {
                    Intent ti = new Intent(PackageCardProjectActivity.this, PackageCardDetailActivity.class);
                    ti.putExtra("servicePackageId", model.getServicePackageId());
                    startActivity(ti);
                }

            }
        });
        adapter.setSelectListener(new PackageCardProjectAdapter2.SelectListener() {
            @Override
            public void onSelectChange() {
                MyLog.e("yang", "111111111111111");
                double totalPrice = 0.00;
                double givePrice = 0.00;
                if (adapter.getSelectedList() != null && adapter.getSelectedList().size() != 0) {
                    for (int i = 0; i < adapter.getSelectedList().size(); i++) {
                        totalPrice += adapter.getSelectedList().get(i).getPrice() * adapter.getSelectedList().get(i).getCurrentCount();
                        givePrice += adapter.getSelectedList().get(i).getGiveAmount() * adapter.getSelectedList().get(i).getCurrentCount();
                        MyLog.e("yang", "totalPrice==" + totalPrice);
                        tvTotalPrice.setText("￥" + String.format("%.2f", totalPrice));
                        tvGivePrice.setText("赠送余额: ￥" + String.format("%.2f", givePrice));
                    }
                } else {
                    tvTotalPrice.setText("￥0.00");
                    tvGivePrice.setText("赠送余额: ￥0.00");
                }
            }
        });
    }


    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(PackageCardProjectActivity.this)) {
                    adapter.pauseMore();
                    easyRecyclerView.showError();
                    return;
                }
                page++;
                getDataList();

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                adapter.clear();
                page = 1;
                adapter.delMap();
                getDataList();
                tvTotalPrice.setText("￥0.00");
                tvGivePrice.setText("赠送余额: ￥0.00");
            }
        }, 1000);
    }


    private void getDataList() {
        OwnerPacStoreServicePackageApi ownerPacStoreServicePackageApi = new OwnerPacStoreServicePackageApi(new HttpOnNextListener<List<PackageCardProjectModel>>() {
            @Override
            public void onNext(List<PackageCardProjectModel> list) {
                setDataList(list);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<PackageCardProjectModel>>>() {
                }.getType();
                BaseResultEntity<List<PackageCardProjectModel>> cacheList = gson.fromJson(cache, type);
                setDataList(cacheList.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(PackageCardProjectActivity.this, e.getMessage());
            }
        }, this, page + "");
        ownerPacStoreServicePackageApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        ownerPacStoreServicePackageApi.setStoreId(SharedPreferencesUtils.getParam(PackageCardProjectActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        ownerPacStoreServicePackageApi.setPackageName("");
        ownerPacStoreServicePackageApi.setPage(page + "");
        ownerPacStoreServicePackageApi.setSize("10");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(ownerPacStoreServicePackageApi);
    }

    private void setDataList(List<PackageCardProjectModel> list) {
        if (list.size() < 9) {
            adapter.stopMore();
        }


        adapter.addAll(list);
        if (adapter.getAllData().size() == 0) {
            easyRecyclerView.setEmptyView(R.layout.view_empty_common);
            easyRecyclerView.showEmpty();
        }
    }


    @OnClick(R.id.tv_select_ok)
    public void llSelectOkOnClick(View view) {
        if (adapter.getSelectedList() == null || adapter.getSelectedList().size() == 0) {
            PhoneUtils.ShowToastMessage(PackageCardProjectActivity.this, "请至少选择一个套餐");
            return;
        }
        double totalPrice = 0.00;
        String servicePackageId = "";
        String numbers = "";
        for (int i = 0; i < adapter.getSelectedList().size(); i++) {
            totalPrice += adapter.getSelectedList().get(i).getPrice() * adapter.getSelectedList().get(i).getCurrentCount();
            numbers += (i == 0 ? "" : ",") + adapter.getSelectedList().get(i).getCurrentCount();
            servicePackageId += (i == 0 ? "" : ",") + adapter.getSelectedList().get(i).getServicePackageId();
        }

        if (totalPrice == 0.00) {
            MyLog.e("yang", "0元套餐购买");
            helpDialog("温馨提示", "是否进行购买套餐", "确定", "取消", numbers, servicePackageId);
        } else {
            Intent ti = new Intent(PackageCardProjectActivity.this, BuyStorePackageActivity.class);
            ti.putExtra("totalPrice", totalPrice);
            ti.putExtra("servicePackageId", servicePackageId);
            ti.putExtra("storeId", (int) SharedPreferencesUtils.getParam(PackageCardProjectActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0));
            ti.putExtra("numbers", numbers);
            startActivity(ti);
        }

    }

    private void helpDialog(String title, String msg, String sure, String cancle, final String numbers, final String servicePackageId) {
        new UniversalDialog(PackageCardProjectActivity.this).builder()
                .setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        payDepositAmount(servicePackageId, numbers);
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }


    private void payDepositAmount(String servicePackageId, String numbers) {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_BUYPACKAGE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PackageCardProjectActivity.this).getSession());
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(PackageCardProjectActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        params.addBodyParameter("useStoreBalance", "true");
        params.addBodyParameter("servicePackageId", servicePackageId);
        params.addBodyParameter("numbers", numbers);
//        params.addBodyParameter("pushPackageId", pushPackageId + "");
        MyLog.e("yang", "params==" + params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "套餐付款onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(PackageCardProjectActivity.this, result);
                if (data != null) {
                    if (data.equals("")) {
                        RxBus.getDefault().post(Constants.BUY_PACKAGE_SUCCESS_CODE, new CommonEvent("购买套餐"));
                        PhoneUtils.ShowToastMessage(PackageCardProjectActivity.this, "购买该套餐成功");
                    }

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "套餐付款onError==" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    @Subscribe(code = Constants.BUY_PACKAGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventBuyPackage(CommonEvent bugPackageEvent) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);

    }

}

